package com.huli.filter;

import cn.hutool.core.lang.Assert;
import com.huli.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class JwtFilterGatewayFilterFactory extends AbstractGatewayFilterFactory<JwtFilterGatewayFilterFactory.Config> {

    public JwtFilterGatewayFilterFactory() {
        super(Config.class);
    }


    @Override
    public GatewayFilter apply(Config config) {

        return (exchange, chain) -> {
            log.info("=======进入认证过滤器========");
            if (exchange.getRequest().getPath().toString().equals("/v2/api-docs")) {
                return chain.filter(exchange);
            } else if (exchange.getRequest().getPath().toString().equals("/adminLogin") ||
                    exchange.getRequest().getPath().toString().equals("/user/login") ||
                    exchange.getRequest().getPath().toString().equals("/owner/login")) {
                return chain.filter(exchange);
            } else {
                HttpHeaders headers = exchange.getRequest().getHeaders();

                List<String> list = headers.get("Authenticate");
                Assert.notNull(list, "没有权限");

                JwtUtils jwtUtils = new JwtUtils();
                jwtUtils.getClaimByToken(list.get(0));

                return chain.filter(exchange);
            }
        };

    }

    static class Config {

    }

}
